package com.erp.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.activiti.engine.HistoryService;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.history.HistoricVariableInstance;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.erp.dao.ApplyDAO;
import com.erp.dao.ExamineDAO;
import com.erp.dao.UserDAO;
import com.erp.domain.TApply;
import com.erp.domain.TExamine;
import com.erp.domain.TUser;
import com.erp.dto.Apply;
import com.erp.dto.Examine;
import com.erp.dto.User;

@Service(value = "examineService")
@Transactional
public class ExamineService {

	/**
	 * 历史记录服务对象
	 */
	@Resource(name = "historyService")
	private HistoryService historyService;

	@Resource(name = "examineDAO")
	private ExamineDAO examineDAO;

	@Resource(name = "applyDAO")
	private ApplyDAO applyDAO;

	@Resource(name = "userDAO")
	private UserDAO userDAO;

	@Deprecated
	public List<Examine> getExamineListOfProcInst(String procInstId) {
		List<Examine> examineList = new ArrayList<Examine>();
		List<HistoricVariableInstance> hisVariableInstList = historyService
				.createHistoricVariableInstanceQuery()//
				.processInstanceId(procInstId)//
				.variableName("examine")//
				.list();

		if (hisVariableInstList != null) {
			for (HistoricVariableInstance hisVariableInst : hisVariableInstList) {
				Examine examineVariable = (Examine) hisVariableInst.getValue();
				examineList.add(examineVariable);
			}
		}

		return examineList;
	}

	/**
	 * 根据申请表获取该申请的审批信息集合
	 * 
	 * @param apply
	 * @return
	 */
	public List<Examine> getExamineListByApply(Apply apply) {
		Map<String, Object> mapping = new HashMap<String, Object>();
		mapping.put("tApply", applyDAO.getById(apply.getId()));
		String hql = "from TExamine e where e.tApply=:tApply order by e.examineTime desc";
		// TODO 手动获取Examine集合而不是通过Apply的get方法，防止死循环
		List<TExamine> tExamineList = examineDAO.list(hql, mapping);
		List<Examine> examineList = new ArrayList<Examine>();
		for (TExamine tExamine : tExamineList) {
			examineList.add(new Examine(tExamine));
		}
		return examineList;
	}

	/**
	 * 获取审批历史记录(根据所有历史流程实例来获取获取所有审批记录，找到某姓名审批的记录添加进来)
	 * 
	 * @param username
	 * @return
	 */
	@Deprecated
	public List<Examine> findExamine(String username) {
		List<Examine> examineList = new ArrayList<Examine>();
		// 获取历史任务列表
		List<HistoricTaskInstance> hisTaskInstList = historyService
				.createHistoricTaskInstanceQuery()//
				.finished()//
				.taskAssignee(username)//
				.list();
		for (HistoricTaskInstance hisTaskInst : hisTaskInstList) {
			String taskId = hisTaskInst.getId();
			HistoricVariableInstance hisVariableInst = historyService
					.createHistoricVariableInstanceQuery()//
					.taskId(taskId)//
					.variableName("examine")//
					.singleResult();
			// 获取流程实例中的审批列表
			if (hisVariableInst != null) {
				Examine examineVariable = (Examine) hisVariableInst.getValue();
				if (username.equals(examineVariable.getAuditor().getName())) {
					examineList.add(examineVariable);
				}
			}

		}
		return examineList;
	}

	/**
	 * 获取某用户的审批历史记录
	 * 
	 * @param auditor
	 * @return
	 */
	public List<Examine> listExamineByUser(User auditor) {
		Map<String, Object> mapping = new HashMap<String, Object>();
		mapping.put("tAuditor", userDAO.getById(auditor.getId()));
		String hql = "from TExamine e where e.tAuditor=:tAuditor order by e.examineTime desc";
		List<TExamine> tExamineList = examineDAO.list(hql, mapping);
		List<Examine> examineList = null;
		if (tExamineList != null) {
			examineList = new ArrayList<Examine>();
			for (TExamine tExamine : tExamineList) {
				examineList.add(new Examine(tExamine));
			}
		}
		return examineList;
	}

	public void add(Apply apply, Examine examine) {
		TApply tApply = new TApply(apply);
		String hql = "from TExamine e where e.tApply=:tApply and ( e.opinion=0 or e.opinion=1 )";
		Map<String, Object> args = new HashMap<String, Object>();
		args.put("tApply", tApply);

		TExamine tExamine = examineDAO.get(hql, args);
		if (tExamine == null) {
			tExamine = new TExamine();
		}
		tExamine.setExamineTime(examine.getExamineTime());
		tExamine.setNote(examine.getNote());
		tExamine.setOpinion(examine.getOpinion());
		tExamine.setTaskId(examine.getTaskId());
		tExamine.settAuditor(new TUser(examine.getAuditor()));
		tExamine.settApply(tApply);

		examineDAO.saveOrUpdate(tExamine);
	}

	/**
	 * 添加下一个审核者的审批意见为待查看
	 * 
	 * @param apply
	 * @param auditor
	 */
	public void addNext(Apply apply, User auditor) {
		Examine examine = new Examine();
		examine.setAuditor(auditor);
		examine.setApply(apply);
		examine.setOpinion(0);
		examine.setTaskId("不存在");

		TExamine tExamine = new TExamine(examine);
		examineDAO.save(tExamine);
	}

	/**
	 * 将审核状态改为已查看
	 * 
	 * @param examine
	 */
	public Examine setWatched(Examine examine) {
		Apply apply = examine.getApply();
		apply.setApplicant(examine.getAuditor());
		TApply tApply = new TApply(apply);
		String hql = "from TExamine e where e.tApply=:tApply and e.opinion=0 ";
		Map<String, Object> args = new HashMap<String, Object>();
		args.put("tApply", tApply);
		TExamine tExamine = examineDAO.get(hql, args);
		if (tExamine != null) {
			tExamine.setOpinion(1);
			examine = new Examine(tExamine);
		}
		return examine;
	}
}
